const router = require('express').Router()
const validateToken = require('../../../common/validateToken')
const status_code = require('../../../common/status_code')
const db = require('../../../db/async-db')
const { to } = require('await-to-js')
const Bee = require('../../../common/bee/bee')

router.get('/get-news-like-list', async (req, resp) => {
  // 错误处理
  function handleError(errCode, error) {
    resp.json({
      code: errCode,
      msg: status_code[errCode],
    })
    console.error(error)
  }

  const { news_id, sqltype, page_index, page_size } = req.query
  if (
    !Bee.StringUtils.isNotBlank(sqltype) ||
    !Bee.StringUtils.isNumber(news_id * 1) ||
    !Bee.StringUtils.isNumber(page_index * 1) ||
    !Bee.StringUtils.isNumber(page_size * 1)
  )
    return handleError(10003, '参数错误')

  // sqltype 个位数: 0 = 降序  1 = 升序

  const sql = `SELECT ui.* FROM news_like nl, news n, userinfo ui WHERE nl.news_id = ? AND nl.news_id = n.id AND ui.id = nl.user_id GROUP BY created_time ${
    Bee.StringUtils.getStrLast(sqltype, 1) === '0' ? 'DESC' : 'ASC'
  } LIMIT ?,?`
  const totalSql = `SELECT count(*) FROM news_like nl, news n, userinfo ui WHERE nl.news_id = ? AND nl.news_id = n.id AND ui.id = nl.user_id`

  const sqlParams = [
    news_id,
    (parseInt(page_index) - 1) * parseInt(page_size),
    parseInt(page_size),
  ]

  // 获取数据总条数
  const [getTotalError, getTotalSuccess] = await to(
    db.query(totalSql, [news_id])
  )
  if (getTotalError || !getTotalSuccess) return handleError(-1, getTotalError)
  const total = getTotalSuccess[0]['count(*)'] // 数据总条数

  const [getNewsLikeError, getNewsLikeSuccess] = await to(
    db.query(sql, sqlParams)
  )
  if (getNewsLikeError || !getNewsLikeSuccess)
    return handleError(-1, getNewsLikeError)

  return resp.json({
    code: 0,
    msg: status_code[0],
    data: {
      list: getNewsLikeSuccess,
      total: total,
    },
  })
})

module.exports = router
